from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import redis
import json
import random
import os
from dotenv import load_dotenv
from tournament_manager import TournamentManager

app = Flask(__name__)
CORS(app)

# 加载环境变量
load_dotenv()

# 加载配置
config_path = os.path.join(os.path.dirname(__file__), 'config.json')
with open(config_path, 'r', encoding='utf-8') as f:
    config = json.load(f)

# 从环境变量覆盖Redis配置（更安全）
redis_config = {
    'host': os.getenv('REDIS_HOST', config['redis']['host']),
    'port': int(os.getenv('REDIS_PORT', config['redis']['port'])),
    'db': int(os.getenv('REDIS_DB', config['redis']['db'])),
    'decode_responses': True
}

# 密码优先从环境变量获取
redis_password = os.getenv('REDIS_PASSWORD')
if not redis_password and 'password' in config['redis']:
    redis_password = config['redis']['password']

if redis_password and redis_password != 'your_redis_password':
    redis_config['password'] = redis_password

# 其他配置也可以从环境变量覆盖
config['total_participants'] = int(os.getenv('TOTAL_PARTICIPANTS', config['total_participants']))

# Redis连接
try:
    redis_client = redis.Redis(**redis_config)
    # 测试连接
    redis_client.ping()
    print("✓ Redis连接成功")
    print(f"  - 主机: {redis_config['host']}:{redis_config['port']}")
    print(f"  - 数据库: {redis_config['db']}")
    print(f"  - 密码: {'已配置' if 'password' in redis_config else '未配置'}")
except Exception as e:
    print(f"✗ Redis连接失败: {e}")
    print("请检查Redis配置和网络连接")
    redis_client = None

# Redis键名
GROUPS_KEY = "badminton:groups"
PARTICIPANTS_KEY = "badminton:participants"

# 初始化比赛管理器
tournament_manager = TournamentManager(redis_client)

def get_group_counts():
    """获取各组当前人数"""
    # 根据配置动态初始化分组
    groups = {group: [] for group in config['groups']}
    if redis_client:
        try:
            stored_groups = redis_client.get(GROUPS_KEY)
            if stored_groups:
                stored_data = json.loads(stored_groups)
                # 确保存储的数据包含所有配置的分组
                for group in config['groups']:
                    if group in stored_data:
                        groups[group] = stored_data[group]
        except Exception as e:
            print(f"获取分组数据失败: {e}")
    return groups

def save_groups(groups):
    """保存分组数据到Redis"""
    if redis_client:
        try:
            redis_client.set(GROUPS_KEY, json.dumps(groups, ensure_ascii=False))
            return True
        except Exception as e:
            print(f"保存分组数据失败: {e}")
    return False

def is_participant_exists(name):
    """检查参与者是否已经摇过号"""
    if redis_client:
        try:
            participants = redis_client.get(PARTICIPANTS_KEY)
            if participants:
                participant_list = json.loads(participants)
                return name in participant_list
        except Exception as e:
            print(f"检查参与者失败: {e}")
    return False

def add_participant(name):
    """添加参与者到已摇号列表"""
    if redis_client:
        try:
            participants = redis_client.get(PARTICIPANTS_KEY)
            participant_list = json.loads(participants) if participants else []
            participant_list.append(name)
            redis_client.set(PARTICIPANTS_KEY, json.dumps(participant_list, ensure_ascii=False))
            return True
        except Exception as e:
            print(f"添加参与者失败: {e}")
    return False

def select_group():
    """智能选择分组，确保各组人数均衡"""
    groups = get_group_counts()
    group_sizes = {group: len(members) for group, members in groups.items()}
    
    # 找出人数最少的组
    min_size = min(group_sizes.values())
    min_groups = [group for group, size in group_sizes.items() if size == min_size]
    
    # 从人数最少的组中随机选择
    return random.choice(min_groups)

@app.route('/')
def index():
    """提供前端页面"""
    return send_from_directory('static', 'index.html')

@app.route('/admin')
def admin():
    """提供管理后台页面"""
    return send_from_directory('static', 'admin.html')

@app.route('/static/<path:filename>')
def static_files(filename):
    """提供静态文件"""
    return send_from_directory('static', filename)

@app.route('/api/config', methods=['GET'])
def get_config():
    """获取配置信息"""
    groups = get_group_counts()
    total_drawn = sum(len(members) for members in groups.values())
    
    return jsonify({
        'total_participants': config['total_participants'],
        'groups': config['groups'],
        'total_drawn': total_drawn,
        'remaining': config['total_participants'] - total_drawn,
        'redis_connected': redis_client is not None
    })

@app.route('/api/groups', methods=['GET'])
def get_groups():
    """获取当前分组情况"""
    groups = get_group_counts()
    return jsonify(groups)

@app.route('/api/draw', methods=['POST'])
def draw():
    """队长抽签接口"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败，无法进行抽签'}), 500

    data = request.get_json()

    if not data or 'name' not in data:
        return jsonify({'error': '请提供队长名称'}), 400

    name = data['name'].strip()
    if not name:
        return jsonify({'error': '队长名称不能为空'}), 400

    try:
        # 使用比赛管理器进行抽签
        success, result, message = tournament_manager.captain_draw(name)
        if success:
            return jsonify({
                'success': True,
                'result': result,
                'message': message,
                'name': name
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'抽签失败: {str(e)}'}), 500

# 保留原有的简单抽签功能作为备用
@app.route('/api/draw-simple', methods=['POST'])
def draw_simple():
    """简单摇号接口（原有功能）"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败，无法进行摇号'}), 500

    data = request.get_json()

    if not data or 'name' not in data:
        return jsonify({'error': '请提供队长名称'}), 400

    name = data['name'].strip()
    if not name:
        return jsonify({'error': '队长名称不能为空'}), 400

    # 检查是否已经摇过号
    if is_participant_exists(name):
        return jsonify({'error': '该队长已经摇过号了'}), 400

    # 检查是否还有名额
    groups = get_group_counts()
    total_drawn = sum(len(members) for members in groups.values())
    if total_drawn >= config['total_participants']:
        return jsonify({'error': '摇号已结束，所有名额已满'}), 400

    # 选择分组
    selected_group = select_group()

    # 更新分组数据
    groups[selected_group].append(name)

    # 保存到Redis
    if save_groups(groups) and add_participant(name):
        return jsonify({
            'success': True,
            'group': selected_group,
            'name': name,
            'groups': groups
        })
    else:
        return jsonify({'error': '保存数据失败，请重试'}), 500

@app.route('/api/reset', methods=['POST'])
def reset():
    """重置所有数据（仅用于测试）"""
    if redis_client:
        try:
            redis_client.delete(GROUPS_KEY)
            redis_client.delete(PARTICIPANTS_KEY)
            return jsonify({'success': True, 'message': '数据已重置'})
        except Exception as e:
            return jsonify({'error': f'重置失败: {e}'}), 500
    return jsonify({'error': 'Redis连接失败'}), 500

# ==================== 比赛管理API ====================

@app.route('/api/tournament/status', methods=['GET'])
def tournament_status():
    """获取比赛状态"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        state = tournament_manager.get_tournament_state()
        config_data = tournament_manager.config

        return jsonify({
            'success': True,
            'tournament_state': state,
            'config': config_data
        })
    except Exception as e:
        return jsonify({'error': f'获取比赛状态失败: {str(e)}'}), 500

@app.route('/api/tournament/register-teams', methods=['POST'])
def register_teams():
    """注册队伍（管理员操作）"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'teams' not in data:
        return jsonify({'error': '请提供队伍信息'}), 400

    teams = data['teams']
    if not isinstance(teams, list) or len(teams) != 10:
        return jsonify({'error': '必须提供10支队伍'}), 400

    # 验证队伍数据格式
    for team in teams:
        if not isinstance(team, dict) or 'name' not in team or 'captain' not in team:
            return jsonify({'error': '队伍信息格式错误，需要包含name和captain字段'}), 400

    try:
        success, state, message = tournament_manager.register_teams(teams)
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'注册队伍失败: {str(e)}'}), 500



@app.route('/api/tournament/match-result', methods=['POST'])
def submit_match_result():
    """提交比赛结果"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'match_id' not in data or 'winner_team_id' not in data:
        return jsonify({'error': '请提供比赛ID和获胜队伍ID'}), 400

    match_id = data['match_id']
    winner_team_id = data['winner_team_id']

    try:
        success, match, message = tournament_manager.submit_match_result(match_id, winner_team_id)
        if success:
            # 获取轮次完成状态
            round_status = tournament_manager.get_round_completion_status(match['round'])

            # 获取更新后的比赛状态
            tournament_state = tournament_manager.get_tournament_state()

            return jsonify({
                'success': True,
                'match': match,
                'message': message,
                'round_status': round_status,
                'tournament_state': tournament_state
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'提交比赛结果失败: {str(e)}'}), 500

@app.route('/api/tournament/advance-round', methods=['POST'])
def advance_round():
    """进入下一轮"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请指定当前轮次'}), 400

    current_round = data['round']

    try:
        # 使用通用的进入下一轮方法
        success, state, message = tournament_manager.advance_to_next_round_generic(current_round)

        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'进入下一轮失败: {str(e)}'}), 500

@app.route('/api/tournament/reset', methods=['POST'])
def reset_tournament():
    """重置比赛"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        if tournament_manager.reset_tournament():
            return jsonify({'success': True, 'message': '比赛已重置'})
        else:
            return jsonify({'error': '重置比赛失败'}), 500
    except Exception as e:
        return jsonify({'error': f'重置比赛失败: {str(e)}'}), 500

@app.route('/api/tournament/check-bye-advancement', methods=['POST'])
def check_bye_advancement():
    """检查并处理轮空晋级"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        data = request.get_json()
        round_name = data.get('round_name')

        if not round_name:
            return jsonify({'error': '缺少轮次名称参数'}), 400

        # 获取当前状态
        state = tournament_manager.get_tournament_state()
        if not state:
            return jsonify({'error': '获取比赛状态失败'}), 500

        # 处理轮空晋级
        tournament_manager._check_and_handle_bye_advancement(state, round_name)

        # 获取更新后的状态
        updated_state = tournament_manager.get_tournament_state()

        return jsonify({
            'success': True,
            'message': '轮空晋级检查完成',
            'tournament_state': updated_state
        })

    except Exception as e:
        return jsonify({'error': f'轮空晋级检查失败: {str(e)}'}), 500

# ==================== 管理后台API ====================

@app.route('/api/admin/config', methods=['GET'])
def get_tournament_config():
    """获取比赛配置"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        config = tournament_manager.get_config()
        return jsonify({
            'success': True,
            'config': config
        })
    except Exception as e:
        return jsonify({'error': f'获取配置失败: {str(e)}'}), 500

@app.route('/api/admin/config', methods=['POST'])
def update_tournament_config():
    """更新比赛配置"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'config' not in data:
        return jsonify({'error': '请提供配置信息'}), 400

    try:
        success, message = tournament_manager.update_config(data['config'])
        if success:
            return jsonify({
                'success': True,
                'message': message,
                'config': tournament_manager.get_config()
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'更新配置失败: {str(e)}'}), 500

@app.route('/api/admin/teams', methods=['GET'])
def get_teams():
    """获取队伍列表"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        state = tournament_manager.get_tournament_state()
        teams = state.get('teams', []) if state else []
        return jsonify({
            'success': True,
            'teams': teams
        })
    except Exception as e:
        return jsonify({'error': f'获取队伍列表失败: {str(e)}'}), 500

@app.route('/api/admin/teams', methods=['POST'])
def add_team():
    """添加队伍"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'name' not in data or 'captain' not in data:
        return jsonify({'error': '请提供队伍名称和队长姓名'}), 400

    try:
        state = tournament_manager.get_tournament_state()
        if not state:
            # 如果没有比赛状态，创建一个新的 - 直接进入第一轮抽签阶段
            state = {
                'current_round': 'round1_main',  # 直接进入第一轮
                'draw_enabled': True,   # 自动开启第一轮抽签
                'draw_stage': 'round1_main',  # 当前抽签阶段为第一轮
                'teams': [],
                'matches': [],
                'round_results': {},
                'champion': None,
                'runner_up': None,
                'drawn_captains': []
            }

            # 为每轮初始化结果存储
            for round_config in tournament_manager.config['rounds']:
                round_name = round_config['name']
                state['round_results'][round_name] = {
                    'advanced': [],
                    'eliminated': [],
                    'groups': {},
                    'completed': False
                }

        # 检查队伍数量限制
        if len(state['teams']) >= tournament_manager.config['total_teams']:
            return jsonify({'error': f"队伍数量已达上限({tournament_manager.config['total_teams']}队)"}), 400

        # 检查队伍名称和队长是否重复
        for team in state['teams']:
            if team['name'] == data['name']:
                return jsonify({'error': '队伍名称已存在'}), 400
            if team['captain'] == data['captain']:
                return jsonify({'error': '队长已存在'}), 400

        # 创建新队伍
        new_team = tournament_manager.create_team(data['name'], data['captain'])
        state['teams'].append(new_team)

        if tournament_manager.save_tournament_state(state):
            return jsonify({
                'success': True,
                'team': new_team,
                'message': '队伍添加成功'
            })
        else:
            return jsonify({'error': '保存队伍失败'}), 500

    except Exception as e:
        return jsonify({'error': f'添加队伍失败: {str(e)}'}), 500

@app.route('/api/admin/teams/<team_id>', methods=['DELETE'])
def delete_team(team_id):
    """删除队伍"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        state = tournament_manager.get_tournament_state()
        if not state:
            return jsonify({'error': '获取比赛状态失败'}), 500

        # 查找并删除队伍
        team_found = False
        for i, team in enumerate(state['teams']):
            if team['id'] == team_id:
                deleted_team = state['teams'].pop(i)
                team_found = True
                break

        if not team_found:
            return jsonify({'error': '队伍不存在'}), 404

        if tournament_manager.save_tournament_state(state):
            return jsonify({
                'success': True,
                'message': '队伍删除成功'
            })
        else:
            return jsonify({'error': '保存状态失败'}), 500

    except Exception as e:
        return jsonify({'error': f'删除队伍失败: {str(e)}'}), 500

# ==================== 新增管理后台API ====================

@app.route('/api/admin/rounds', methods=['POST'])
def add_round():
    """添加比赛轮次"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请提供轮次信息'}), 400

    try:
        success, message = tournament_manager.add_round(data['round'])
        if success:
            return jsonify({
                'success': True,
                'message': message,
                'config': tournament_manager.get_config()
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'添加轮次失败: {str(e)}'}), 500

@app.route('/api/admin/rounds/<round_name>', methods=['PUT'])
def update_round(round_name):
    """修改轮次配置"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请提供轮次信息'}), 400

    try:
        success, message = tournament_manager.update_round(round_name, data['round'])
        if success:
            return jsonify({
                'success': True,
                'message': message,
                'config': tournament_manager.get_config()
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'修改轮次失败: {str(e)}'}), 500

@app.route('/api/admin/rounds/<round_name>', methods=['DELETE'])
def delete_round(round_name):
    """删除轮次"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        success, message = tournament_manager.delete_round(round_name)
        if success:
            return jsonify({
                'success': True,
                'message': message,
                'config': tournament_manager.get_config()
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'删除轮次失败: {str(e)}'}), 500

@app.route('/api/admin/current-round', methods=['POST'])
def set_current_round():
    """设置当前轮次"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请提供轮次名称'}), 400

    try:
        success, state, message = tournament_manager.set_current_round(data['round'])
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'设置当前轮次失败: {str(e)}'}), 500

@app.route('/api/admin/available-next-rounds', methods=['GET'])
def get_available_next_rounds():
    """获取可以切换的下一轮列表"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        success, rounds, message = tournament_manager.get_available_next_rounds()
        if success:
            return jsonify({
                'success': True,
                'available_rounds': rounds,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'获取可用轮次失败: {str(e)}'}), 500

@app.route('/api/admin/enable-draw', methods=['POST'])
def enable_draw():
    """开启指定轮次的抽签"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请提供轮次名称'}), 400

    try:
        success, state, message = tournament_manager.enable_draw_for_round(data['round'])
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'开启抽签失败: {str(e)}'}), 500

@app.route('/api/admin/disable-draw', methods=['POST'])
def disable_draw():
    """关闭抽签"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        success, state, message = tournament_manager.disable_draw()
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'关闭抽签失败: {str(e)}'}), 500

@app.route('/api/admin/round-status/<round_name>', methods=['GET'])
def get_round_status(round_name):
    """获取轮次状态"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        round_status = tournament_manager.get_round_completion_status(round_name)
        return jsonify({
            'success': True,
            'round_status': round_status
        })
    except Exception as e:
        return jsonify({'error': f'获取轮次状态失败: {str(e)}'}), 500

@app.route('/api/admin/revival-round', methods=['POST'])
def toggle_revival_round():
    """开启/关闭复活赛"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data or 'enabled' not in data:
        return jsonify({'error': '请提供轮次名称和开启状态'}), 400

    try:
        success, state, message = tournament_manager.toggle_revival_round(data['round'], data['enabled'])
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'设置复活赛失败: {str(e)}'}), 500

@app.route('/api/admin/elimination-mode', methods=['POST'])
def toggle_elimination_mode():
    """开启/关闭淘汰赛模式"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'enabled' not in data:
        return jsonify({'error': '请提供淘汰赛模式状态'}), 400

    try:
        success, state, message = tournament_manager.toggle_elimination_mode(data['enabled'])
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'设置淘汰赛模式失败: {str(e)}'}), 500

@app.route('/api/admin/enable-draw', methods=['POST'])
def enable_draw_for_round():
    """为指定轮次开启抽签"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    data = request.get_json()
    if not data or 'round' not in data:
        return jsonify({'error': '请提供轮次名称'}), 400

    try:
        success, state, message = tournament_manager.enable_draw_for_round(data['round'])
        if success:
            return jsonify({
                'success': True,
                'tournament_state': state,
                'message': message
            })
        else:
            return jsonify({'error': message}), 400
    except Exception as e:
        return jsonify({'error': f'开启抽签失败: {str(e)}'}), 500

@app.route('/api/health', methods=['GET'])
def health():
    """健康检查接口"""
    return jsonify({
        'status': 'ok',
        'redis_connected': redis_client is not None,
        'redis_config': {
            'host': redis_config['host'],
            'port': redis_config['port'],
            'db': redis_config['db'],
            'password_configured': 'password' in redis_config
        }
    })

@app.route('/api/test/fix-bye-bug', methods=['POST'])
def test_fix_bye_bug():
    """测试修复复活赛轮空bug的接口"""
    if not redis_client:
        return jsonify({'error': 'Redis连接失败'}), 500

    try:
        data = request.get_json() or {}
        round_name = data.get('round_name', 'round1_revival')

        # 获取当前状态
        state = tournament_manager.get_tournament_state()
        if not state:
            return jsonify({'error': '获取比赛状态失败'}), 500

        print(f"\n=== 测试修复复活赛轮空bug ===")
        print(f"轮次: {round_name}")

        # 调用我们的修复方法
        tournament_manager._check_revival_bye_after_draw(state, round_name)

        # 保存状态
        if tournament_manager.save_tournament_state(state):
            return jsonify({
                'success': True,
                'message': f'已检查并修复 {round_name} 的轮空问题',
                'tournament_state': state
            })
        else:
            return jsonify({'error': '保存状态失败'}), 500

    except Exception as e:
        return jsonify({'error': f'修复失败: {str(e)}'}), 500

if __name__ == '__main__':
    print("=" * 60)
    print("羽毛球大赛分组摇号系统 - 安全版")
    print("=" * 60)
    print(f"总参与人数: {config['total_participants']}")
    print(f"分组: {', '.join(config['groups'])}")
    print(f"Redis状态: {'已连接' if redis_client else '连接失败'}")
    print("访问地址: http://localhost:5000")
    print("健康检查: http://localhost:5000/api/health")
    print("=" * 60)
    
    debug_mode = os.getenv('DEBUG', 'True').lower() == 'true'
    use_reloader = os.getenv('USE_RELOADER', 'True').lower() == 'true'

    print(f"Debug模式: {'开启' if debug_mode else '关闭'}")
    print(f"自动重启: {'开启' if use_reloader else '关闭'}")

    app.run(
        debug=debug_mode,
        host='0.0.0.0',
        port=5000,
        use_reloader=use_reloader
    )
